<template>
  <!--案场信息管理-->
  <el-row style="height:100%">
    <page @buttons="configPermissions">
      <pageheader :event="'mallPopUp'" :isShow="buttonPermissions.isAdd">
        案场信息管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <el-row>
            <Cascader
              :value.sync="company_id_arr"
              :options.sync="options"
              :width="'300px'"
              :changeEvent="'mallChange'"
            >所属企业：
            </Cascader>
            <SearchInput
              style="margin-left: 20px"
              @mallsearch="mallsearch"
              :searchEvent="'mallsearch'"
              :value="keywords"
              :searchText="'请输入案场名称'"
              ref="clearText"
            >搜索：
            </SearchInput>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="所属集团" prop="company_name" align="center" width="120" sortable></el-table-column>
            <el-table-column label="案场名称" prop="case_name" align="center" width="120" sortable></el-table-column>
            <el-table-column label="案场编码" prop="case_code" align="center" width="120" sortable></el-table-column>
            <el-table-column label="案场时区" prop="time_zone" align="center" width="80" sortable></el-table-column>
            <el-table-column label="案场描述" prop="case_desc" align="center"></el-table-column>
            <el-table-column  v-if="buttonPermissions.isOpModify || buttonPermissions.isBaseModify || buttonPermissions.isWatch || buttonPermissions.isDel"
                              label="操作" align="center" width="300">
              <template slot-scope="scope">
                <el-button v-if="buttonPermissions.isBaseModify"
                           @click="mallData(scope.row,1)" size="small">基础修改</el-button>
                <el-button  v-if="buttonPermissions.isOpModify"
                          @click="mallData(scope.row,2)"  size="small">运维修改</el-button>
                <el-button v-if="!buttonPermissions.isOpModify && !buttonPermissions.isBaseModify && buttonPermissions.isWatch"
                          @click="mallData(scope.row,1)" size="small">详情</el-button>
                <el-button v-if="buttonPermissions.isDel" type="danger"
                           @click="mallDel(scope.row)"  size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <el-dialog  v-dialogDrag :title="pageTitle" :visible.sync="isShow" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false" width="1200px">
          <el-form :model="ruleForm" :rules="rules" inline ref="ruleForm" label-width="200px">
            <el-form-item label="所属企业" prop="company_id_arr">
              <el-cascader
                v-model="ruleForm.company_id_arr"
                :options="options"
                :props="{ expandTrigger: 'hover' }"
                :disabled="isDisabled"
                :isClearable="false"
                @change="companyChange"
                size="small"
                style="width:300px"></el-cascader>
            </el-form-item>
            <el-form-item label="案场名称" prop="case_name">
              <el-input v-model="ruleForm.case_name" size="small"  style="width:300px" ></el-input>
            </el-form-item>
            <el-form-item label="案场编码" prop="case_code">
              <el-input v-model="ruleForm.case_code" size="small" @change="caseCodeChange" :disabled="update_type == 1" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="案场地址" prop="addName">
                <el-input v-model="addressName"  size="small" readonly :disabled="update_type == 1" style="width:300px">
                  <el-button v-if="update_type != 1" slot="append" @click.stop="isShowTabs = true">修改</el-button>
                </el-input>
                <div v-show="isShowTabs" class="add-name" @click.stop>
                  <i class="icon iconfont icon-guanbi" @click="isShowTabs = false"></i>
                  <el-tabs v-model="ruleForm.activeName" @tab-click="handleClick">
                    <el-tab-pane :label="ruleForm.countryName" name="country">
                      <ul class="add-name-ul">
                        <li v-for="item in ruleForm.countryOption"
                            :key="item.id"
                            :class="{isActive:item.isActive}"
                            @click="clickCountry(item)">{{item.name}}</li>
                        <li class="icon-delete" @click="clickDelete('country')"><i class="el-icon-delete"></i></li>
                      </ul>
                    </el-tab-pane>
                    <el-tab-pane :label="ruleForm.provinceName" name="province">
                      <ul class="add-name-ul">
                        <li v-for="item in ruleForm.provinceOption"
                            :key="item.id"
                            :class="{isActive:item.isActive}"
                            @click="clickProvince(item)">{{item.name}}</li>
                        <li class="icon-delete" @click="clickDelete('province')"><i class="el-icon-delete"></i></li>
                      </ul>
                    </el-tab-pane>
                    <el-tab-pane :label="ruleForm.cityName" name="city">
                      <ul class="add-name-ul">
                        <li v-for="item in ruleForm.cityOption"
                            :key="item.id"
                            :class="{isActive:item.isActive}"
                            @click="clickCity(item)">{{item.name}}</li>
                        <li class="icon-delete" @click="clickDelete('city')"><i class="el-icon-delete"></i></li>
                      </ul>
                    </el-tab-pane>
                    <el-tab-pane :label="ruleForm.districtName" name="district">
                      <ul class="add-name-ul">
                        <li v-for="item in ruleForm.districtOption"
                            :key="item.id"
                            :class="{isActive:item.isActive}"
                            @click="clickDistrict(item)">{{item.name}}</li>
                        <li class="icon-delete" @click="clickDelete('district')"><i class="el-icon-delete"></i></li>
                      </ul>
                    </el-tab-pane>
                  </el-tabs>
                </div>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="ruleForm.address" size="small" :disabled="update_type == 1" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="案场时区" prop="time_zone">
              <el-input v-model="ruleForm.time_zone" size="small" :disabled="update_type == 1" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="案场类型" prop="case_type">
              <el-select v-model="ruleForm.case_type" :disabled="update_type == 1" placeholder="请选择" size="small" style="width:300px">
                <el-option label="购物中心" value="0"></el-option>
                <el-option label="店铺" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数据存储空间" prop="table_code">
              <el-select v-model="ruleForm.table_code" :disabled="update_type != 0" placeholder="请选择" size="small" style="width:300px">
                <el-option
                  v-for="item in tableCodeOption"
                  :key="item.table_code"
                  :label="item.table_code"
                  :value="item.table_code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签管理" prop="tags_name">
              <el-input v-model="ruleForm.tags_name" size="small" :readonly="update_type != 1" :disabled="update_type == 1" style="width:300px;">
                <el-button v-if="update_type != 1" slot="append" @click="opentagsDialog">修改</el-button>
              </el-input>
              <div v-if="update_type != 1" @click="opentagsDialog" class="onClickDiv"></div>
            </el-form-item>
            <el-form-item label="营业时间" prop="opening_hours_name">
              <el-input v-model="ruleForm.opening_hours_name" size="small" :readonly="update_type != 1" :disabled="update_type == 1" style="width:300px;">
                <el-button v-if="update_type != 1" slot="append" @click="openingOpen">修改</el-button>
              </el-input>
              <div v-if="update_type != 1" @click="openingOpen" class="onClickDiv"></div>
            </el-form-item>
            <el-form-item label="案场描述" prop="case_desc">
              <el-input v-model="ruleForm.case_desc" size="small"  type="textarea" style="width:300px"></el-input>
            </el-form-item>
            <!-- <el-form-item label="营业时间关联案场所属区域" prop="is_use" v-if="update_type==2">
              <el-radio-group v-model="ruleForm.is_syn_area" @change="yysjbdClick" size="small"  >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <br v-if="update_type==2" /> -->
            <el-form-item label="是否启用" prop="is_use">
              <el-radio-group v-model="ruleForm.is_use" size="small" :disabled="update_type == 1">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">未启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button v-if="(update_type == 0 && buttonPermissions.isAdd) || (update_type == 1 && buttonPermissions.isBaseModify) || (update_type == 2 && buttonPermissions.isOpModify)"
              type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>
          <!--穿梭框-->
          <el-dialog title="标签管理" :visible.sync="showTransfer" width="1000px" top="20vh"
                     @close="tagsClose"  append-to-body style="text-align: center" :modal="false" :close-on-click-modal="false">
            <Transfer :value.sync="ls_tags_arr"
                      :options="transferData"
                      :tagsTypeList="tagsTypeList"
                      :event="'transferChange'"
                      @transferChange="transferChange"
                      v-if="tagsIsShow"
            ></Transfer>
            <div slot="footer" class="dialog-footer">
              <el-button @click="showTransfer = false" size="small">取 消</el-button>
              <el-button type="primary" @click="confirmTransfer" size="small">保 存</el-button>
            </div>
          </el-dialog>

          <!--营业时间-->
          <el-dialog title="营业时间" class="yysj" :visible.sync="showOpening" top="20vh" append-to-body width="60%"
                     style="text-align: center" :modal="false" :close-on-click-modal="false" @opened="openedOpening" @close="closeOpening">
            <el-table :data="openingDataTable" size="small" ref="openingTable"
                      row-key="id" highlight-current-row @current-change="handleCurrentChange">
              <el-table-column label="营业时间名称" prop="name" align="center"></el-table-column>
              <el-table-column label="营业时间描述" prop="info" align="center"></el-table-column>
              <el-table-column label="是否是公共营业时间" prop="isCommon" align="center"></el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template slot-scope="scope">
                  <el-button @click="openingData(scope.row)" size="small">详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--营业时间详情-->
            <el-dialog title="营业时间详情" :visible.sync="showOpeningContent" top="20vh"
                       append-to-body :modal="false" :close-on-click-modal="false">
              <el-form label-width="120px">
                <el-form-item label="名称：" prop="name">
                  <el-input v-model="openingContent.name" readonly size="small" style="width:70%"></el-input>
                </el-form-item>
                <el-form-item label="描述：" prop="info">
                  <el-input v-model="openingContent.info" readonly type="textarea" size="small" style="width:70%" maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="营业时间列表：" prop="item_list">
                  <el-table :data="openingContent.item_list">
                    <el-table-column align="center" width="60px">
                      <template slot-scope="scope">
                        <i slot="reference" class="el-icon-sort"></i>
                        {{scope.row.level}}
                      </template>
                    </el-table-column>
                    <el-table-column label="描述" prop="info" align="center"></el-table-column>
                    <el-table-column label="是否是假日" prop="is_holiday" align="center">
                      <template slot-scope="scope">
                        <el-tag v-if="scope.row.is_holiday == 1" size="mini" type="success">是</el-tag>
                        <el-tag v-else size="mini" type="danger">否</el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="开始日期" prop="start_day" align="center"></el-table-column>
                    <el-table-column label="结束日期" prop="end_day" align="center"></el-table-column>
                    <el-table-column label="营业时间" prop="open_time" align="center"></el-table-column>
                    <el-table-column label="结束时间" prop="close_time" align="center">
                      <template slot-scope="scope">
                        <span v-if="scope.row.close_time_next">{{scope.row.close_time_next}}</span>
                        <span v-else>{{scope.row.close_time}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="星期" prop="weeks" align="center"></el-table-column>
                  </el-table>
                </el-form-item>
              </el-form>
            </el-dialog>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="showOpening = false" size="small">确 定</el-button>
            </div>
          </el-dialog>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .yysj{
    .el-dialog{
        .el-dialog__body{
          .el-table{
            .el-table__body-wrapper{
              .el-table__body{
                .el-table__row{
                  cursor: pointer;
                  &.current-row{
                    .is-center{
                      &:first-child{
                        &::after{
                          border: 2px solid #6689f1;
                        }
                        &::before{
                          content: '';
                          display: block;
                          width:6px;
                          height: 6px;
                          border-radius: 50%;
                          background:#6689f1;
                          position: absolute;
                          top:50%;
                          transform: translateY(-50%);
                          left:24px;
                          
                        }
                      }
                    }
                  }
                  .is-center{
                     &:first-child{
                      position: relative;
                      &::after{
                        content: '';
                        display: block;
                        width:10px;
                        height:10px;
                        border: 2px solid #ccc;
                        border-radius:50%;
                        position: absolute;
                        left:20px;
                        top:50%;
                        transform: translateY(-50%);
                        
                      }
                    }
                    
                  }
                }
              }
            }
          }
        }
        
    }
  }
  table td {
    line-height: 26px;
  }
  .page-content {
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
  }
  .openingTable{
    .el-table__body-wrapper{
      cursor: pointer;
    }
  }
  .add-name{
    width: 500px;
    border: 1px solid #ccc;
    position: absolute;
    padding: 5px 10px;
    background: #fff;
    z-index:99;
    .icon-guanbi{
      position: absolute;
      top: 0px;
      right: 5px;
      font-size: 16px;
      color: #ccc;
      z-index: 100;
      cursor: pointer;
    }
    .add-name-ul{
      width: 100%;
      padding: 5px 10px;
      position: relative;
      li{
        display: inline-block;
        margin: 5px;
        font-size: 12px;
        color: #0c78dd;
        line-height: 12px;
        padding: 2px 3px;
        cursor:pointer;
      }
      li:hover{
        color:#e4393c
      }
      .isActive{
        color: #e4393c;
      }
      .icon-delete{
        position: absolute;
        bottom: 0px;
        right: 0px;
      }
    }
  }
  .onClickDiv{
    display: inline-block;
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    cursor: pointer;
  }
  .el-dialog{
    max-width: 1300px;
    .el-transfer-panel{
      width:395px;
    }
  }

</style>
<script>
import page from "@/components/page/page";
import pageheader from "@/components/page/pageheader";
import SearchInput from "@/components/sys/assembly/searchinput";
import Cascader from "@/components/sys/assembly/elcascader";
import Transfer from "@/components/sys/assembly/transfer";

export default {
  data() {
    let validateCaseName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入案场名称'));
      } else {
        let str =  /[`~!@#$%^&*\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*\-+={}|《》？：“”【】、；‘’，。、]/im;
        if(str.test(value)){
          return callback(new Error('案场名称不得使用特殊符号！'));
        }
        if(value.length >=30){
          return callback(new Error('案场名称长度不能超过30个字！'));
        }
        callback();
      }
    };
    let validateAddName = (rule,value,callback) =>{
      if(this.ruleForm.country == ''){
        callback()
      }else{
        if(this.ruleForm.city == ''){
          return callback(new Error('案场地址选择最少输入至市一级'))
        }
        callback()
      }
    }

    return {
      id:this.$route.query.id,
      pageTitle: "案场信息",
      isShow: false,//是否显示模态框
      isDisabled:false,//是否是修改状态
      dataTable:[],//表格数据
      company_id:'',//所属企业选中id
      company_id_arr:[],//所属企业选中id arr
      keywords:'',//搜索查询
      transferData:[],//穿梭框data参数
      tagsTypeList:[],//tags类型列表
      showTransfer:false,//是否显示穿梭框模态框
      pagination:{
        total:0,//总条目数
        currentPage:1,//当前页数
        pageSize:10,//每页显示条目个数
        pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
      },//表格分页参数
      nowList:{},//临时ruleForm参数
      ls_tags_arr:[],   //临时tags数组
      tagsIsShow:false,  //tags选择模态框
      ruleForm: {
        case_name: '',//案场名称
        company_id_arr: [],//所属企业arr
        company_id: '',//所属企业str
        case_desc: '',//案场描述
        case_code: '',//案场编码
        is_use:1,//是否启用
        // is_syn_area:0,  //是否将营业时间同步到下属区域  默认否
        tags:'',//标签id列表
        tags_name:'',//标签名称列表
        tags_arr:[],//标签id列表
        time_zone: '+8',//案场时区
        table_code:'',//数据存储空间
        opening_hours_id:'',//营业时间id
        opening_hours_name:'',//营业时间名称
        case_type:'0',//案场类型

        countryOption:[],//案场地址：国家list
        provinceOption:[],//案场地址：省市list
        cityOption:[],//案场地址：市list
        districtOption:[],//案场地址：区list

        country:'',//案场地址：国家
        province:'',//案场地址：省市
        city:'',//案场地址：市
        district:'',//案场地址：区

        countryName:'国家',
        provinceName:'省/直辖市',
        cityName:'市',
        districtName:'区',

        addName:'国家/省/直辖市/市/区',//显示的地址名称
        activeName:'country',//当前显示的标签
        address:'',//详细地址

      },//模态框form表单
      rules: {
        case_name: [{ required: true,validator:validateCaseName, trigger: "blur" }],
        company_id_arr: [{ required: true, message: "请选择所属企业",trigger:'change'}],
        table_code: [{ required: true, message: "请选择数据存储空间",trigger:'change'}],
        case_code: [{ required: true, message: "请输入案场编码",trigger:'blur'}],
        addName: [{ required: true, validator:validateAddName,trigger:'blur'}],
      },//form表单验证
      update_type:0,//当打开模态框时判断为何种状态：0，新增，1：基础修改，2：运维修改
      options:[],//级联控件 所属企业
      handleWidth:270,//表格操作宽度

      showOpening:false,//是否显示营业时间模态框
      openingDataTable:[],//营业时间列表
      showOpeningContent:false,//是否显示营业时间详情模态框
      openingContent:{
        name:'',
        info:'',
        item_list:[],
      },//营业时间详情

      isShowTabs:false,//是否显示地址选择
      buttonPermissions:{
        isAdd:false,
        isDel:false,
        isBaseModify:false,
        isOpModify:false,
        isWatch:false,
      },
      tableCodeOption:[],//数据存储空间列表

    };
  },
  components: {
    page,
    pageheader,
    SearchInput,//搜索框组件
    Cascader,//级联选择器组件
    Transfer,//穿梭框组件
  },
  created() {
    // console.log(this.id,'id');
    //判断是否有按钮权限
    if(sessionStorage.buttonPermissions){
      this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
    }

    //初始化
    this.getReady();
    this.getTableStored();

    this.getDistrice()
    .then(data=>{
      this.ruleForm.countryOption = data
      this.ruleForm.countryOption[0].isActive = true
    })
    .catch(err=>{
      this.defaultProvince()
      console.log(err);
      this.$message.warning('获取国家列表失败')
    })
  },
  mounted() {
    //添加按钮click事件
    this.$Bus.$on('mallPopUp',() =>{
      this.isShow = true;
      this.isDisabled = false;
      this.update_type = 0
    });
    //所属企业change事件
    this.$Bus.$on("mallChange", data => {
      // console.log(data);
      this.company_id = data.slice(-1)[0];
      this.$refs.clearText.clearText();//调用组件内方法清空值
      this.keywords = ''//清空搜索存储的临时变量
      this.$Bus.$emit('Loading',true)
      this.caseInfoList(this.company_id)
    });
    this.clickBody()
  },
  beforeDestroy(){
    //销毁Bus绑定事件
    this.$Bus.$off("mallPopUp");
    this.$Bus.$off("mallChange")
  },
  computed:{
    addressName(){
      return this.ruleForm.countryName + '/' + this.ruleForm.provinceName + '/' + this.ruleForm.cityName +'/'+ this.ruleForm.districtName
    },
    districts_node_location(){
      return this.ruleForm.country + '-' + this.ruleForm.province + '-' + this.ruleForm.city +'-'+ this.ruleForm.district
    }
  },
  watch:{
    isShowTabs(){
      this.$refs.ruleForm.validateField('addName')
    }
  },
  methods: {
    //控制点击关闭案场地址模态框
    clickBody(){
      let _body = document.body
      _body.addEventListener('click',()=>{
        this.isShowTabs = false
      })
    },
    //表格序号显示方法
    indexMethod(index){
      return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
    },
    //配置按钮权限，根据权限不同调整表头渲染参数
    configPermissions(val){
      let buttonPermissions = val
      let menuButtonPermissions = [];//按钮权限数组
      buttonPermissions.forEach(e =>{
        for(let key in e){
          if(key == 'menu_code'){
            menuButtonPermissions.push(e[key])
          }
        }
      });
      this.buttonPermissions.isAdd = menuButtonPermissions.includes('mallAdd') ? true : false; //是否有新增权限
      this.buttonPermissions.isDel = menuButtonPermissions.includes('mallDelete') ? true : false; //是否有删除权限
      this.buttonPermissions.isBaseModify = menuButtonPermissions.includes('mallBaseModify') ? true : false; //是否有基础修改权限
      this.buttonPermissions.isOpModify = menuButtonPermissions.includes('mallOpModify') ? true : false; //是否有运维修改权限
      this.buttonPermissions.isWatch = menuButtonPermissions.includes('mallWatch') ? true : false; //是否有查看权限

    },
    //页面初始化
    getReady(){
      //获取企业树
      let getTree = ()=>{
        let p = new Promise((res,rej)=>{
          let url = '/sys/report_assist_new/company_tree';
          this.$api.get(url)
          .then(data => {
            if(data == '10001'){
              this.$message.error('无权操作该数据')
              this.$Bus.$emit('Loading',false);
              return
            }
            if(data){
              recursion(data.data);
              function recursion(val) {
                if(val.length){
                  for(let i in val){
                    val[i].value = val[i].id;
                    val[i].label = val[i].company_name;
                    val[i].parent_id_str =val[i].parent_name_list==null?'':val[i].parent_name_list.join('/');
                    if(val[i].children && val[i].children.length){
                      recursion(val[i].children)
                    }else{
                      delete val[i].children
                    }
                  }
                }
              }
              this.options = data.data;
              //判断是否传递了参数
              if(this.$route.query.id){
                this.company_id = this.$route.query.id
                res(this.company_id)
              }else{
                this.company_id = data.data[0].id
                this.company_id_arr.push(data.data[0].id)
                res(data.data[0].id)
              }
            }else{
              rej()
            }
          })
          .catch(err=>{
             console.log(err);
            this.options = [];
            rej()
          })
        })
        return p
      }
      //获取标签列表
      let getTagsList = ()=>{
        let p = new Promise((res,rej)=>{
          let url = '/sys/tags/list'
          this.$api.get(url)
          .then(data=>{
            if(data == '10001'){
              this.$message.error('无权操作该数据')
              this.$Bus.$emit('Loading',false);
              return
            }
            console.log(data,'获取标签列表');
            if(data){
              let list = data.data
              for(let i in list){
                list[i].key = list[i].id;
                list[i].label = list[i].name;
              }
              this.transferData = list
              res()
              }else{
              rej()
            }
          })
          .catch(err=>{
             console.log(err);
            this.transferData = [];
            rej()
          })
        })
        return p
      }
      let gatTagsTypeList = ()=>{
        let p = new Promise((res,rej)=>{
          let url = '/sys/tags/type_list'
          this.$api.get(url)
          .then(data=>{
            if(data == '10001'){
              this.$message.error('无权操作该数据')
              this.$Bus.$emit('Loading',false);
              return
            }
            console.log(data,'获取标签类型列表');
            if(data){
              this.tagsTypeList = data.data ? data.data : []
              res()
            }else{
              rej()
            }
          })
          .catch(err=>{
             console.log(err);
            this.tagsTypeList = [];
            rej()
          })
        })
        return p
      }
      //判断是否存有菜单，如果没有则调用接口
      Promise.all([getTree(),getTagsList(),gatTagsTypeList()])
      .then((data)=>{
        console.log(this.tagsTypeList,'tagsTypeList');
        this.transferData = this.transferData.map(x=>{
          for(let i in this.tagsTypeList){
            if(this.tagsTypeList[i].type == x.type){
              x.typeName = this.tagsTypeList[i].name
            }
          }
          return x
        })
        console.log(this.transferData,'this.transferData');
        // console.log('全部执行完毕');
        //拿到所属企业中第一个企业的id，调用获取案场列表
        let id=this.$route.query.id
        if(id){
          let idArr = id.split('-').filter(x=>{
            return x
          })
          this.company_id_arr = idArr
          this.company_id = idArr[idArr.length-1]
          this.caseInfoList(this.company_id)
        }else{
          this.caseInfoList(data[0])
        }


      })
      .catch(()=>{
        console.log('出错了');
        this.$Bus.$emit('Loading',false)
      })
    },
    //数据存储空间列表
    getTableStored(){
      let url ='/sys/db/all_table_stored'
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        // console.log(data);
        if(data){
          this.tableCodeOption = data.data
          this.ruleForm.table_code = data.data[0].table_code
        }
      })
    },
    //获取标签列表
    getTagsList(){
      let url = '/sys/tags/list'
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          let list = data.data
          for(let i in list){
            list[i].key = list[i].id;
            list[i].label = list[i].name;
          }
          this.transferData = list
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.transferData = [];
        this.$Bus.$emit('Loading',false)
      })
    },
    //获取案场列表
    caseInfoList(id='',page = 1,page_size = 10,keywords = ''){
      let url = '/sys/case-info/list?company_id='+ id +
        '&page='+ page +'&page_size=' + page_size + '&keywords=' + encodeURIComponent(keywords);

      this.$api.get(url)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        //判断接口返回正常
        if(data&&data.data)
        {
          let _data = data.data;
          this.dataTable = _data.dataList ? _data.dataList : [];
          this.pagination.total = _data.dataCount;
          this.pagination.currentPage = _data.pageCode;
          this.pagination.pageSize = _data.pageSize;
        }        
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.dataTable = []
        this.$Bus.$emit('Loading',false)
      })
    },

    //关闭模态框
    closeDialog(formName){
      this.$refs[formName].resetFields();
      this.ruleForm.id = '';
      this.ruleForm.company_id = '';
      this.ruleForm.opening_hours_id = '';
      this.ruleForm.opening_hours_name = '';

      this.defaultCountry()
      this.ruleForm.activeName = 'country'
      this.openingDataTable = [];
      this.$set(this.ruleForm,'tags_arr',[]);//清空标签id列表
      this.$Bus.$emit('Loading',false);
    },
    //获取案场查看详情
    getCaseInfo(id){
      let url = '/sys/case-info/get?case_info_id=' + id
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        // console.log(data);
        if(data){
          let _data = data.data
          _data.tags_arr = _data.tags ? _data.tags.split(',') : [];
          let transferData = this.transferData
          let val = _data.tags_arr.map(Number)//将数组中元素字符串转数字类型
          _data.tags_arr = val
          let tags_name = ''
          _data.company_id_arr = _data.company_node_location.split('-')
          _data.company_id_arr.splice(-1,1)
          for(let i in transferData){
            for(let ii in val){
              if(val[ii] == transferData[i].id){
                if(tags_name == ''){
                  tags_name = transferData[i].name
                }else{
                  tags_name += ',' + transferData[i].name
                }
              }
            }
          }
          _data.tags_name = tags_name;
          _data.case_type = String(_data.case_type)
          _data.districts_node_location = _data.districts_node_location ? _data.districts_node_location.split('-') : null
          //判断是否存在案场地址
          if(_data.districts_node_location){
            this.ruleForm.country = _data.districts_node_location[0]
            this.ruleForm.province = _data.districts_node_location[1]
            this.ruleForm.city= _data.districts_node_location[2]
            this.ruleForm.district= _data.districts_node_location[3]

            let getAddress = async ()=>{
              this.getDistriceName(this.ruleForm.countryOption,this.ruleForm.country,'country')

              let provinceData = await this.getDistrice(this.ruleForm.country)
              this.ruleForm.provinceOption = provinceData
              this.getDistriceName(this.ruleForm.provinceOption,this.ruleForm.province,'province')

              let cityData = await this.getDistrice(this.ruleForm.province)
              this.ruleForm.cityOption = cityData
              this.getDistriceName(this.ruleForm.cityOption,this.ruleForm.city,'city')

              let districtData = await this.getDistrice(this.ruleForm.city)
              this.ruleForm.districtOption = districtData
              this.getDistriceName(this.ruleForm.districtOption,this.ruleForm.district,'district')
            }
            getAddress().then(()=>{

            })
            .catch(err=>{
              this.$message.warning(err)
              this.$Bus.$emit('Loading',false);
            })
          }

          this.ruleForm = Object.assign(this.ruleForm,_data);
          this.getOpeningList(_data.company_id)
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //案场编码change事件，判断案场编码是否存在
    caseCodeChange(val){
      if (val) {
        //校验案场编码是否存在
        let url = '/sys/case-info/exist_code?case_code='+ val;
        this.$api.get(url)
        .then(data =>{
          if(data.data){
            this.$message.error('案场编码已存在')
            this.ruleForm.case_code = ''
          }
        })
      }
    },
    //穿梭框change事件,存一个临时变量
    transferChange(val){
      this.ls_tags_arr = val
    },
    //打开tags模态框
    opentagsDialog(){
        this.ls_tags_arr=this.ruleForm.tags_arr;
        this.tagsIsShow=true;
        this.showTransfer=true;
    },
    //关闭tags
    tagsClose(){
      this.tagsIsShow=false;
    },
    //保存修改标签，将transferArr转换成string
    confirmTransfer(){
      let list = this.transferData
      let val = this.ls_tags_arr
      this.ruleForm.tags = val.join(',')
      this.ruleForm.tags_name = ''
      for(let i in list){
        for(let ii in val){
          if(val[ii] == list[i].id){
            if(this.ruleForm.tags_name == ''){
              this.ruleForm.tags_name += list[i].name
            }else{
              this.ruleForm.tags_name += ',' + list[i].name
            }
          }
        }
      }
      this.ruleForm.tags_arr=this.ls_tags_arr;
      this.showTransfer = false;
    },
    //每页显示条目个数change事件
    sizeChange(val){
      this.$Bus.$emit('Loading',true)
      this.caseInfoList(this.company_id,this.pagination.currentPage,val,this.keywords)
    },
    //分页change事件
    currentChange(val){
      this.$Bus.$emit('Loading',true)
      this.caseInfoList(this.company_id,val,this.pagination.pageSize,this.keywords)
    },
    //搜索按钮点击事件
    mallsearch(data) {
      this.$Bus.$emit('Loading',true)
      this.keywords = data;
      this.caseInfoList(this.company_id,1,this.pagination.pageSize,data)
    },
    //模态框保存按钮
    confirmDialog(formName){
      let data = {};
      let model = null
      let url = ''
      console.log(this.districts_node_location,'districts_node_location');

      this.$refs[formName].validate(valid => {
        if (valid) {
          model = this.$refs[formName].model;
          model.company_id = model.company_id_arr.length !== 0 ? model.company_id_arr.slice(-1)[0] : '';
          if (this.update_type == 1) {
            data.case_desc = model.case_desc
            data.case_name = model.case_name
            url = "/sys/case-info/update_base?id="+ model.id;
            this.$Bus.$emit('Loading',true)
            this.modifyMall(url, data);
          }
          else if(this.update_type == 2){
            if(model.case_code == ''){
              this.$message.error('请输入案场编码')
              return
            }
            data.case_desc = model.case_desc;
            data.case_name = model.case_name;
            data.case_code = model.case_code;
            data.is_use = model.is_use;
            data.tags = model.tags;
            data.time_zone = model.time_zone;
            data.case_type = model.case_type;
            data.opening_hours_id = this.ruleForm.opening_hours_id;
            data.districts_node_location = this.districts_node_location
            
            this.$confirm('是否将营业时间级联到下属区域?', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              showClose:false,
              closeOnClickModal:false,
              closeOnPressEscape:false,
              type: 'warning'
            }).then(() => {
                data.is_syn_area_opening_hours = 1;
                url = "/sys/case-info/update_op?id="+ model.id;
                this.$Bus.$emit('Loading',true);
                this.modifyMall(url, data);
            }).catch(() => {
                data.is_syn_area_opening_hours = 0;
                url = "/sys/case-info/update_op?id="+ model.id;
                this.$Bus.$emit('Loading',true);
                this.modifyMall(url, data);
            });
          }else{
            data.case_code = model.case_code;
            data.table_code  = model.table_code;
            data.is_use = model.is_use;
            data.tags = model.tags;
            data.time_zone = model.time_zone;
            data.case_desc = model.case_desc;
            data.case_name = model.case_name;
            data.company_id = model.company_id;
            data.case_type = model.case_type;
            data.opening_hours_id = this.ruleForm.opening_hours_id;
            data.districts_node_location = this.districts_node_location
            url = "/sys/case-info/add";
            this.$Bus.$emit('Loading',true)
            // console.log(data,'data');
            this.addMall(url, data);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //新增保存
    addMall(url, data) {
      this.$api.post(url, data)
      .then(data => {
        // console.log(data);
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.$api.get('/sys/report_assist_new/refresh_auth_cache')
          .then(data=>{}).catch(err=>{ console.log(err);})
          this.caseInfoList(this.company_id,this.pagination.currentPage,this.pagination.pageSize,this.keywords)
          this.isShow = false
          this.$message({
            message: "新增成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
    },
    //修改保存
    modifyMall(url,data){
      this.$api.put(url, data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.$api.get('/sys/report_assist_new/refresh_auth_cache')
          .then(data=>{}).catch(err=>{ console.log(err);})
          this.caseInfoList(this.company_id,this.pagination.currentPage,this.pagination.pageSize,this.keywords)
          this.isShow = false
          this.$message({
            message: "修改成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
    },
    //删除按钮点击事件
    mallDel(data){
      this.$confirm("是否删除‘"+ data.case_name +"’？","提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center:true
      })
      .then(() => {
        this.$Bus.$emit('Loading',true)
        this.delData(data.id);
      })
      .catch(() => {});
    },
    //删除接口
    delData(id) {
      let url = "/sys/case-info/del";
      let data = {
        id:id
      }
      this.$api.delete(url,data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.caseInfoList(this.company_id,this.pagination.currentPage,this.pagination.pageSize,this.keywords)
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }else{
          this.$Bus.$emit('Loading',false)
        }
      })
    },
    //修改按钮点击事件
    mallData(data,n){
      //判断点击的是基础修改，还是运维修改
      this.update_type = n;
      this.nowList = data;
      this.isShow = true;
      this.isDisabled = true;
      this.$Bus.$emit('Loading',true)
      this.getCaseInfo(data.id)
    },
    //营业时间绑定到下属区域提示
    // yysjbdClick(val){
    //   if(val==1)
    //   {
    //     this.$alert("该选项为'是'，则该案场所属区域营业时间将被修改", '提示', {
    //       confirmButtonText: '知道了',
    //       callback: action => {
    //       }
    //     });
    //   }
    // },
    //点击营业时间修改按钮
    openingOpen(){
      if(!this.ruleForm.company_id){
        this.$message.warning('请选选择所属企业')
        return
      }
      this.showOpening = true
    },
    //打开营业时间模态框
    openedOpening(){
      this.$nextTick(()=>{
        this.openingDataTable.map(x=>{
          if(x.id == this.ruleForm.opening_hours_id){
            this.$refs.openingTable.setCurrentRow(x);
          }
        })
      })
    },
    //关闭营业时间模态框
    closeOpening(){
      this.$refs.openingTable.clearSelection();
    },
    //获取营业时间列表
    getOpeningList(company_id = ''){
      let url = '/sys/opening_hours/list?company_id='+ company_id
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        // console.log(data);
        if(data){
          let _data = data.data
          this.openingDataTable = _data.map(x=>{
            x.isCommon = x.is_common ? '是' : '否';
            if(this.ruleForm.opening_hours_id && x.id == this.ruleForm.opening_hours_id){
              this.ruleForm.opening_hours_name = x.name
            }
            return x
          });
        }else{
          this.openingDataTable = []
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.openingDataTable = [];
        this.$Bus.$emit('Loading',false)
      })
    },
    //打开营业时间详情
    openingData(data){
      data.item_list.sort((x,y)=>{
        if(x.level > y.level) return 1
        if(x.level < y.level) return -1
        return 0
      })
      this.showOpeningContent = true
      this.openingContent.name = data.name
      this.openingContent.info = data.info
      this.openingContent.item_list = data.item_list
    },
    //选中营业时间事件
    handleCurrentChange(data){
      if(data){
        this.$set(this.ruleForm,'opening_hours_id',data.id)
        this.$set(this.ruleForm,'opening_hours_name',data.name)
      }
    },
    //将已选择的监测点禁止取消
    checkSelectable(row){
      if(this.ruleForm.opening_hours_id){
        return !(row.id == this.ruleForm.opening_hours_id)
      }else{
        return true
      }
    },
    companyChange(data){
      this.ruleForm.company_id_arr = data
      this.ruleForm.company_id = data.slice(-1)[0]
      this.ruleForm.opening_hours_id = ''
      this.ruleForm.opening_hours_name = ''
      this.openingDataTable = []
      this.getOpeningList(data.slice(-1)[0])
      this.$refs.ruleForm.validateField('company_id_arr')//触发form表单中校验所属企业是否选择
    },

    // //案场地址hover方法
    // mouseenterAdd(){
    //   this.isShowTabs = this.update_typeg == 1 ? false : true;
    // },
    // mouseleaveAdd(){
    //   this.isShowTabs = false;
    // },
    handleClick(){

    },
    //选中了国家
    clickCountry(item){
      this.defaultProvince();
      this.getDistrice(item.id)
      .then((data)=>{
        this.ruleForm.provinceOption = data
        this.ruleForm.provinceOption[0].isActive = true
        this.$Bus.$emit('Loading',false);
      })
      .catch(err=>{
        console.log(err);
        this.$message.warning('获取省/直辖市级列表失败')
        this.$Bus.$emit('Loading',false);
      })

      for(let i in this.ruleForm.countryOption){
        if(this.ruleForm.countryOption[i].id == item.id) {
          this.ruleForm.countryOption[i].isActive = true
          this.ruleForm.countryName = this.ruleForm.countryOption[i].name
          this.ruleForm.country = item.id
        }else{
          this.ruleForm.countryOption[i].isActive = false
        }
      }
      this.ruleForm.activeName = 'province'
    },
    //选中了省/直辖市
    clickProvince(item){
      this.defaultCity()
      this.getDistrice(item.id)
      .then((data)=>{
        this.ruleForm.cityOption = data
        this.ruleForm.cityOption[0].isActive = true
        this.$Bus.$emit('Loading',false);
      })
      .catch(err=>{
        console.log(err);
        this.$message.warning('获取市级列表失败')
        this.$Bus.$emit('Loading',false);
      })

      for(let i in this.ruleForm.provinceOption){
        if(this.ruleForm.provinceOption[i].id == item.id){
          this.ruleForm.provinceOption[i].isActive = true
          this.ruleForm.provinceName = this.ruleForm.provinceOption[i].name
          this.ruleForm.province = item.id
        }else{
          this.ruleForm.provinceOption[i].isActive = false
        }
      }
      this.ruleForm.activeName = 'city'
    },
    //选中了市
    clickCity(item) {
      this.defaultDistrict()
      this.getDistrice(item.id)
      .then((data)=>{
        this.ruleForm.districtOption = data
        this.ruleForm.districtOption[0].isActive = true
        this.$Bus.$emit('Loading',false);
      })
      .catch(err=>{
        console.log(err);
        this.$message.warning('获取区级列表失败')
        this.$Bus.$emit('Loading',false);
      })

      for (let i in this.ruleForm.cityOption) {
        if (this.ruleForm.cityOption[i].id == item.id){
          this.ruleForm.cityOption[i].isActive = true
          this.ruleForm.cityName = this.ruleForm.cityOption[i].name
          this.ruleForm.city = item.id
        }else{
          this.ruleForm.cityOption[i].isActive = false
        }
      }
      this.ruleForm.activeName = 'district'
    },
    //选中了区
    clickDistrict(item) {
      //点击了接口提供的街道则有id，如果选择自己填写则没有id
      if(item.id){
        for (let i in this.ruleForm.districtOption) {
          if (this.ruleForm.districtOption[i].id == item.id){
            this.ruleForm.districtOption[i].isActive = true
            this.ruleForm.districtName = this.ruleForm.districtOption[i].name
            this.ruleForm.district = item.id
          }else{
            this.ruleForm.districtOption[i].isActive = false
          }
        }
      }else{
        this.ruleForm.districtName = ''
      }
      this.isShowTabs = false
    },
    //删除按钮
    clickDelete(item){
      switch (item) {
        case 'country':
          this.defaultCountry()
          break
        case 'province':
          this.defaultProvince()
          break
        case 'city':
          this.defaultCity()
          break
        case 'district':
          this.defaultDistrict()
          break
      }
    },
    //恢复默认国家级
    defaultCountry(){
      this.ruleForm.country='';
      this.ruleForm.province='';
      this.ruleForm.city='';
      this.ruleForm.district='';
      this.ruleForm.countryName='国家';
      this.ruleForm.provinceName='省/直辖市';
      this.ruleForm.cityName='市';
      this.ruleForm.districtName='区';
      this.ruleForm.provinceOption=[];
      this.ruleForm.cityOption=[];
      this.ruleForm.districtOption=[];
    },

    //恢复默认省级
    defaultProvince(){
      this.ruleForm.province='';
      this.ruleForm.city='';
      this.ruleForm.district='';
      this.ruleForm.provinceName='省/直辖市';
      this.ruleForm.cityName='市';
      this.ruleForm.districtName='区';
      this.ruleForm.cityOption=[];
      this.ruleForm.districtOption=[];
    },
    //恢复默认市级
    defaultCity(){
      this.ruleForm.city='';
      this.ruleForm.district='';
      this.ruleForm.cityName='市';
      this.ruleForm.districtName='区';
      this.ruleForm.districtOption=[];
    },
    //恢复默认区级
    defaultDistrict(){
      this.ruleForm.district='';
      this.ruleForm.districtName='区';
    },

    //根据父级行政区域id获取下属行政区列表
    getDistrice(id = ''){
      let p = new Promise((res,rej)=>{
        this.$api.get('/sys/map/get-districe-by-parent-id?parentId='+ id)
        .then(data=>{
          if(data == '10001'){
            rej('无权操作该数据')
            return
          }
          if(data){
            console.log(data);
            res(data.data)
          }else{
            rej()
          }
        })
        .catch(err=>{
          rej(err)
        })
      })
      return p
    },

    getDistriceName(data,id,level){
      for(let i in data){
        if(data[i].id == id) {
          data[i].isActive = true
          this.ruleForm[level+'Name'] = data[i].name
          this.ruleForm[level] = id
        }else{
          data[i].isActive = false
        }
      }
    }
  },
};
</script>
